package com.qhgrain.app.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.service.UserService;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.Unit;
import com.qhgrain.gway.util.HttpUtil;

@Controller
@RequestMapping("/unit")
public class UnitController {
	private static Logger LOG = LoggerFactory.getLogger(UnitController.class);
	private static final String SERVICEURL = ConfigUtil.getProperties(UrlEnum.UNIT);

	@Autowired
	private UserService userService;
	/**
	 * 根据ID禁用机构
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/deleteByIds")
	@ResponseBody
	public JSONObject deleteByIds(Model model,  String ids,  String status) {

		JSONObject result = new JSONObject();
		if (StringUtil.isBlank(ids) || StringUtil.isBlank(status)) {
			result.put("code", "fail");
			result.put("msg", "机构id和状态不能为空");
		} else {

			try {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("unitIds", ids);
				
				paramMap.put("status", status);
				String vo = HttpUtil.post(SERVICEURL+ "/iunitservice/updateStatus",paramMap);
				JSONObject voJson = JSONObject.parseObject(vo);
				if ("1".equals(voJson.getString("state"))) {
					result.put("code", "success");
					result.put("msg", "成功");
				} else {
					result.put("code", "fail");
					result.put("msg", "系统出错，禁用失败!");
					LOG.error("禁用机构,api失败..."
							+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error("禁用机构，系统出错...." + e.getStackTrace());
				result.put("code", "fail");
				result.put("msg", "系统出错");
			}
		}

		return result;
	}

	/**
	 * 获取所有机构
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String queryUnits() {
		//查询条件的机构类型
		return "unit/unit_list";
	}
	//局部刷新table
	@RequestMapping(value="/list/table")
	public String queryUnitsForTable(Model model, String pageNo, String pageSize,
			Unit unit,String pUnitName,String unitId){
		if (StringUtils.isEmpty(pageNo) || !StringUtil.isInteger(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)|| !StringUtil.isInteger(pageSize)) {
			pageSize = "10";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		
		if (StringUtil.isNotBlank(pUnitName)) {
			model.addAttribute("pUnitName",pUnitName);
		}
		if (StringUtil.isNotBlank(unit.getUnitName())) {
			map.put("unitName", unit.getUnitName().trim());
			model.addAttribute("unitName", unit.getUnitName().trim());
		}
		if (null != unit.getUnitType()) {
			map.put("unitType", unit.getUnitType());
			model.addAttribute("unitType", unit.getUnitType());
		}
		if (StringUtil.isNotBlank(unit.getParentId())) {
			map.put("parentId", unit.getParentId().trim());
			model.addAttribute("parentId", unit.getParentId().trim());
		}
		if (StringUtil.isNotBlank(unitId)) {
			map.put("parentId", unitId.trim());
			model.addAttribute("parentId", unitId.trim());
		}
		if (StringUtil.isNotBlank(unit.getUnitNO())) {
			map.put("unitNO", unit.getUnitNO().trim());
			model.addAttribute("unitNO", unit.getUnitNO().trim());
		}
		Integer status = unit.getStatus();
		if (status != null) {
			map.put("status", status);
			model.addAttribute("status", status);
		}
		
		map.put("page",pageNo );
		map.put("row",pageSize);
		
		String requestVo;
		try {
			//获取当前登录用户机构Id(用于获取当前登录用户所在及其子机构,admin用户获取全部)
			String currentUserLoginName = IndexController.getLoginName();
			if(StringUtil.isNotBlank(currentUserLoginName) && !"admin".equals(currentUserLoginName)){
				String currentUserUnitId = this.userService.findByLoginName(currentUserLoginName).getUnitId();
				map.put("currentUserUnitId", currentUserUnitId);
			}
			
			requestVo = HttpUtil.postFormParams(SERVICEURL, "/iunitservice/queryUnit", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);

			if ("1".equals(voJson.getString("state"))) {
				JSONArray list = voJson.getJSONArray("data");
				

				PageBean<Object> pageBean = new PageBean<Object>(
						Integer.parseInt(pageNo), Integer.parseInt(pageSize));
				pageBean.setData(list);
				int count =voJson.getInteger("exceptionMsg");
				pageBean.setTotalCount(count);
				pageBean.setCurrentPage(new Integer(pageNo));
				model.addAttribute("pageBean", pageBean);
				return "unit/unit_list_table";
			} else {
				LOG.error("机构查询,api出错。。。。" + voJson.getString("exceptionMsg"));
			}

		} catch (IOException e) {
			LOG.error("机构查询出错。。。。" , e);
		}

		return "unit/unit_list_table";
	
	}
	
	/**
	 * 跳转 编辑/修改 机构页面
	 * 
	 * @param unit
	 * @return
	 */
	@RequestMapping(value = "/goEdit")
	public String goEdit( String unitId,String currentPage,String pageSize, Model model) {
		JSONObject unit = new JSONObject();
		String parentUnitName = "";
		if (!StringUtil.isBlank(unitId)) {
			Map<String,String> params=new HashMap<String,String>();
			params.put("unitId", unitId);
			try {
				String jsonstr = HttpUtil.get(SERVICEURL+"/iunitservice/getUnitById", params);
				JSONObject voJson = JSONObject.parseObject(jsonstr);
				if ("1".equals(voJson.getString("state"))) {
					unit = voJson.getJSONObject("data");
					//查询父机构名
					try {
						Map<String,String> pparams=new HashMap<String,String>();
						pparams.put("unitId", unit.get("parentId").toString());
						String pjsonstr = HttpUtil.get(SERVICEURL+"/iunitservice/getUnitById", pparams);
						JSONObject pvoJson = JSONObject.parseObject(pjsonstr);
						JSONObject punit = pvoJson.getJSONObject("data");
						parentUnitName = punit.getString("unitName");
					} catch (Exception e) {
						LOG.error("获取父机构信息失败..."
								+ voJson.getString("exceptionMsg"));
					}
					
				} else {
					LOG.error("编辑机构，从api获取对象信息失败..."
							+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}

		}
		model.addAttribute("unit", unit);
		model.addAttribute("parentUnitName", parentUnitName);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pageSize", pageSize);
		return "unit/unit_edit";
	}
	/**
	 * 
	 * 2016年3月29日 下午8:09:49  
	 * @tags 保存机构
	 * @author zhaoyq
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject save(Model model,Unit unit){
		JSONObject result = new JSONObject();
		try {
			if(unit == null ){
				result.put("code", "fail");
				result.put("msg","请确保数据填写完整");
			}else{
				String unitNO = unit.getUnitNO();
				String unitName = unit.getUnitName();
				Integer unitType = unit.getUnitType();
				String parentId = unit.getParentId();
				if( StringUtil.isBlank(unitName)  ){
					result.put("code", "fail");
					result.put("msg","机构名不能为空");
				}else{
					String vo ;
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("unitNO", unitNO);
					map.put("unitName", unitName);
					map.put("unitType", unitType);
					map.put("parentId", parentId);
					map.put("status", unit.getStatus());
					if(StringUtil.isBlank(unit.getUnitId())){
						//新增
						vo = HttpUtil.postFormParams(SERVICEURL, "/iunitservice/addUnit", map);
					}else{
						//修改
						map.put("unitId", unit.getUnitId());
						vo = HttpUtil.postFormParams(SERVICEURL, "/iunitservice/editUnit", map);
					}
					JSONObject voJson = JSONObject.parseObject(vo);
					if("1".equals(voJson.getString("state"))){
						result.put("code", "success");
						result.put("msg", "成功");
					}else{
						result.put("code", "fail");
						result.put("msg", "系统出错，操作失败!");
						LOG.error("保存机构,api失败..."+voJson.getString("exceptionMsg"));
					}
				}
			}
			
		} catch (Exception e) {
			LOG.error("保存机构系统出错。。。"+e.getMessage());
		}
		return result;
	}

	/**
	 * 根据ID获取机构
	 * 
	 * @param unitId
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/getUnitById/{unitId}")
	public String getUnitById(@PathVariable String unitId, Model model) throws IOException {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("unitId", unitId);
		paramMap.put("status", "0");
		String vo = HttpUtil.get(SERVICEURL+ "/iunitservice/updateStatus",
				paramMap);
		JSONObject voJson = JSONObject.parseObject(vo);
		model.addAttribute("unit", voJson);
		return "unit/unit_edit";
	}

	
}
